package com.cskaoyan.utils;


import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 创建日期: 2022/11/16 16:13
 *
 * @author ciggar
 */
public class JDBCUtils2 {

    static Connection connection = null;

    static String url = null;
    static String username = null;
    static String password = null;
    static String driverClassName = null;

    static {
        try {

            // 从配置文件中获取url、username、password的值
            Properties properties = new Properties();
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
            properties.load(fileInputStream);

            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driverClassName = properties.getProperty("driver");

//            System.err.println("从配置文件中获取到的url:" + url );
//            System.err.println("从配置文件中获取到的username:" + username );
//            System.err.println("从配置文件中获取到的password:" + password );


            // 1. 注册驱动
            //DriverManager.registerDriver(new Driver());
            // new Driver();
            Class.forName(driverClassName);

            // 2. 获取连接
            connection = DriverManager.getConnection(url,username,password);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    // 获取连接
    public static Connection getConnection(){

        return connection;

    }


    // 获取新连接
    public static Connection getNewConnection(){

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;

    }


    // 关闭资源
    public static void closeResources(ResultSet resultSet ,Statement statement, Connection connection){
        try {
            if (resultSet != null) resultSet.close();
            if (statement != null) statement.close();
            if (connection != null) connection.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
